import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { login, logout } from "@/clientApi/login";
import { removeToken, setToken } from "@/utils/auth";
import { AppConfig } from "@/config/appConfig";
import { globalMessage } from "@/utils/message";


const userSlice = createSlice({
    name: 'users',
    initialState: {
        token: '',
    },
    reducers: {
        // 储存token
        SET_TOKEN: (state, { payload: token }) => {
            state.token = token || null
            setToken(token)
        },
        REMOVE_TOKEN: () => {
            removeToken()
        },

    },

    // https://zhuanlan.zhihu.com/p/382487951
    // 一般用于处理异步操作，这里是Pending: 当异步操作开始时，Fulfilled: 当异步操作成功完成时，Rejected: 当异步操作遇到错误时
    extraReducers: (builder) => {
        // builder.addCase(getUserInfoSlice.pending, () => {
        //     // console.log('pending 进行中');
        // })
        // builder.addCase(getUserInfoSlice.fulfilled, (state, { payload }) => {
        //     // console.log( '1 fulfilled', { payload, state } )
        // })
        // builder.addCase(getUserInfoSlice.rejected, (state, action) => {
        //     // userSlice.actions.CLEAR_USER_INFO()
        // })
    }


})

export const { SET_TOKEN, REMOVE_TOKEN } = userSlice.actions
export const getLogin = createAsyncThunk("user/login",
    async (params: any, thunkAPI) => {
        try {
            const res: any = await login(params.data)
            if (res.code === 200) {
                if (res.data.access_token) {
                    thunkAPI.dispatch(SET_TOKEN(res.data.access_token))
                    if (typeof window !== 'undefined') {
                        window.location.href = AppConfig.BASE_PAGE_PARAMETER
                    }
                }

            } else {
                globalMessage().warning(res.msg || '登录失败')
            }
        } catch (error) {
            console.log(error, 'error')
        }
    })



// export const getUserInfoSlice = createAsyncThunk(
//     "user/getUserInfo",
//     async (params, thunkAPI) => {
//         try {
//             const {code, data} = await getUserInfo({token: getCookie('token') || thunkAPI.getState().users.token})
//             if (code === 200) {
//                 const result = {
//                     username: data.username || data.nickName,
//                     avatar: data.avatar || '',
//
//                 }
//                 thunkAPI.dispatch(SET_USER_INFO(result))
//                 return result;
//             }else{
//                 thunkAPI.dispatch(CLEAR_USER_INFO())
//                 return thunkAPI.rejectWithValue(data.message || '登录失败')
//                 // return Promise.reject( '登录请求错误' )
//             }
//         }catch (err) {
//             console.log('err', err)
//             thunkAPI.dispatch(CLEAR_USER_INFO())
//             return thunkAPI.rejectWithValue(err.response.data || '登录失败')
//         }
//     }
// )
//
export const loginOut = createAsyncThunk(
    'user/loginOut',
    async (params, thunkAPI) => {
        try {
            // const response = {
            //     code: 200,
            //     message: 'success'
            // }
            // const { code, data } = response
            const res: any = await logout()

            if (res.code === 200) {
                thunkAPI.dispatch(REMOVE_TOKEN())
                location.href = '/';
                // window.location.reload()
                return {}
            } else {
                return thunkAPI.rejectWithValue(res.data.message || '登出失败')
            }
        } catch (err:any) {
            return thunkAPI.rejectWithValue(err.response.data || '登出失败')
        }
    }
)


const userReducer = userSlice.reducer
export default userReducer
